package com.wiloon.androidx.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;

/**
 * Miscellaneous agent utility methods.
 */
public class AgentUtils {

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isAvailable());
    }

    /**
     * Get file from Bytes[]
     */
    public static File bytesToFile(byte[] btyes, String outputFile) {
        File file = null;
        BufferedOutputStream stream = null;
        FileOutputStream fstream = null;
        try {
            file = new File(outputFile);
            fstream = new FileOutputStream(file);

            stream = new BufferedOutputStream(fstream);
            stream.write(btyes);
            stream.close();
            fstream.close();
        } catch (FileNotFoundException e) {
            Log.e("AgentUtils", "getFileFromBytes", e);
        } catch (IOException e) {
            Log.e("AgentUtils", "getFileFromBytes", e);
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    Log.e("AgentUtils", "getFileFromBytes", e);
                }
            }
            if (fstream != null) {
                try {
                    fstream.close();
                } catch (IOException e) {
                    Log.e("AgentUtils", "getFileFromBytes", e);
                }
            }
        }
        return file;
    }

    public static Bitmap bytesToBitmap(byte[] param) {
        if (param != null && param.length > 0) {
            return BitmapFactory.decodeByteArray(param, 0, param.length);
        }
        return null;
    }

    public static byte[] bitmapToBytes(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        byte[] result = null;
        ByteArrayOutputStream os = null;
        try {
            os = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
            result = os.toByteArray();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    Log.e("AgentUtils", "bitmapToBytes", e);
                }
            }
        }
        return result;
    }

    /**
     * dip to pixels
     *
     * @param context
     * @param dip
     * @author cuijk
     */
    public static int dipToPixels(Context context, int dip) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f);
    }

    /**
     * pixels to dip
     *
     * @param context
     * @param pixels
     * @author zhangb
     */
    public static int pixelsToDip(Context context, int pixels) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pixels / scale + 0.5f);

    }

    public static int getScreenWidth(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    public static int getScreenHeight(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    /**
     * Decode a bitmap
     */
    public static Bitmap decodeBitmap(String path) {
        Bitmap bitmap = null;
        // Decode image size
        BitmapFactory.Options bfo = new BitmapFactory.Options();
        bfo.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, bfo);
        // Calculate scale
        int scale = (int) Math
                .round(Math.sqrt(bfo.outHeight * bfo.outWidth) / 720);
        if (scale < 1) {
            scale = 1;
        }
        // Decode with inSampleSize
        BitmapFactory.Options resize = new BitmapFactory.Options();
        resize.inSampleSize = scale;
        bitmap = BitmapFactory.decodeFile(path, resize);
        return bitmap;
    }

    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    public static Bitmap getSmallBitmap(String filePath, int width, int height) {
        Bitmap bitmap = decodeBitmap(filePath);

        while (!isSmallBitmap(bitmap)) {
            bitmap = setSmallBitmap(filePath, width, height);
            width = (int) (width * 0.8);
            height = (int) (height * 0.8);
        }
        return bitmap;
    }

    public static Bitmap getSmallBitmap(String filePath) {
        Bitmap bitmap = decodeBitmap(filePath);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        while (!isSmallBitmap(bitmap)) {
            bitmap = setSmallBitmap(filePath, width, height);
            width = (int) (width * 0.8);
            height = (int) (height * 0.8);
        }
        return bitmap;
    }

    public static Bitmap setSmallBitmap(String filePath, int width, int height) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, width, height);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

    public static boolean isSmallBitmap(Bitmap bitmap) {
        boolean flag = true;
        byte[] imgBytes = null;
        if (null != bitmap) {
            imgBytes = bitmapToByteArray(bitmap);
        }
        if (null != imgBytes && imgBytes.length / 1024 > 400) {
            flag = false;
        }
        return flag;
    }

    /**
     * Bitmap convert ByteArray
     */
    public static byte[] bitmapToByteArray(Bitmap bitmap) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * ByteArray convert Bitmap
     */
    public static Bitmap byteArrayToBitmap(byte[] bytes) {
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return bitmap;
    }

    /**
     * Compare ByteArray
     */
    public static boolean byteArrayEquals(byte[] b1, byte[] b2) {
        if (b1 == null && b2 == null) {
            return true;
        }
        if (b1 == null || b2 == null) {
            return false;
        }
        if (b1.length != b2.length) {
            return false;
        }
        for (int i = 0; i < b1.length; i++) {
            if (b1[i] != b2[i]) {
                return false;
            }
        }
        return true;
    }

    /**
     * close keyboard
     */
    public static void closeKeyBoard(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    public static String getToday() {
        Calendar c = Calendar.getInstance();
        return AgentConstants.BLANK + c.get(Calendar.YEAR)
                + c.get(Calendar.MONTH) + c.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 设置子控件TextView不可用
     *
     * @param dp
     */
    public static void setDisabledEditTexts(ViewGroup dp) {
        for (int x = 0, n = dp.getChildCount(); x < n; x++) {
            View v = dp.getChildAt(x);
            if (v instanceof EditText) {
                v.setFocusable(false);
                v.setClickable(false);
                v.setFocusableInTouchMode(false);
                v.setLongClickable(false);
            } else if (v instanceof ViewGroup) {
                setDisabledEditTexts((ViewGroup) v);
            }
        }
    }

    public static String getAppPath() {
        StringBuffer sb = new StringBuffer();
        sb.append(Environment.getExternalStorageDirectory().getPath());
        sb.append(File.separator);
        sb.append(AgentConstants.AGENT_NAME);
        sb.append(File.separator);
        return sb.toString();
    }

    public static String getCachePath() {
        StringBuffer sb = new StringBuffer();
        sb.append(getAppPath());
        sb.append(AgentConstants.CACHE_PATH);
        sb.append(File.separator);
        return sb.toString();
    }

    public static String getLogPath() {
        StringBuffer sb = new StringBuffer();
        sb.append(getAppPath());
        sb.append(AgentConstants.LOG_PATH);
        sb.append(File.separator);
        return sb.toString();
    }

    public static String getDownloadPath() {
        StringBuffer sb = new StringBuffer();
        sb.append(getAppPath());
        sb.append(AgentConstants.DOWNLOAD_PATH);
        sb.append(File.separator);
        return sb.toString();
    }

    public static void saveBitmapFile(Bitmap bitmap, String filename) {
        File file = new File(filename);// 将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用来判断服务是否运行.
     *
     * @param className 判断的服务名字
     * @return true 在运行 false 不在运行
     */
    public static boolean isServiceRunning(Context mContext, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(30);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

}
